/*
 * www.acooly.cn Inc.
 * Copyright (c) 2018 All Rights Reserved
 */

/*
 * 修订记录:
 * zhangpu@acooly.cn 2018-01-31 16:37 创建
 */
package com.acooly.module.openapi.client.provider.yibao.notify;


import com.acooly.core.common.exception.BusinessException;
import com.acooly.core.common.web.servlet.AbstractSpringServlet;
import com.acooly.core.utils.Servlets;
import com.acooly.core.utils.Strings;
import com.acooly.module.openapi.client.api.notify.NotifyHandlerDispatcher;
import com.acooly.module.openapi.client.provider.yibao.OpenAPIClientYibaoProperties;
import com.acooly.module.openapi.client.provider.yibao.YibaoConstants;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * @author zhangpu 2018-01-31 16:37
 */
@Slf4j
public class YibaoApiServiceClientServlet extends AbstractSpringServlet {

    private NotifyHandlerDispatcher notifyHandlerDispatcher;

    private static final int SUCCESS_RESPONSE_CODE = 200;
    private static final String SUCCESS_RESPONSE_BODY = "SUCCESS";
    private static final String FAILED_RESPONSE_BODY = "SUCCESS";
    private static final String DEFAULT_NOTIFY_DISPATCHER_BEAN_NAME = "clientNotifyHandlerDispatcher";

    public static final String SUCCESS_RESPONSE_CODE_KEY = "success_response_code";
    public static final String SUCCESS_RESPONSE_BODY_KEY = "success_response_body";
    public static final String NOTIFY_DISPATCHER_BEAN_NAME_KEY = "NOTIFY_DISPATCHER_BEAN_NAME_KEY";
    @Autowired
    private OpenAPIClientYibaoProperties openAPIClientYibaoProperties;

    @Override
    public void doService(HttpServletRequest request, HttpServletResponse response) {
        JSONObject resultJson = new JSONObject();
        resultJson.put("returnCode","SUCCESS");
        try {
            StringBuilder stringBuilder = new StringBuilder();
            InputStream inputStream = request.getInputStream();
            BufferedReader bufferedReader = null;
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            }
            if(Strings.isBlank(stringBuilder.toString())) {
                throw new BusinessException("异步通知报文为空");
            }
            log.info("Yibao异步通知: {}",stringBuilder.toString());
            Map<String, String> notifyData = Maps.newHashMap();
            notifyData.put(YibaoConstants.REQUEST_PARAM_NAME,stringBuilder.toString());
            String requestUrl = Servlets.getRequestPath(request);
            notifyHandlerDispatcher.dispatch(requestUrl, notifyData);
            response.setStatus(SUCCESS_RESPONSE_CODE);
            Servlets.writeResponse(response, resultJson.toJSONString(), null);
        } catch (Exception e) {
            resultJson.put("returnCode","FAILED");
            Servlets.writeResponse(response,  resultJson.toJSONString(), null);
        }
    }

    @Override
    public void doInit() {
        super.doInit();
        notifyHandlerDispatcher = getBean(getDispatcherBeanName(), NotifyHandlerDispatcher.class);
    }

    @Override
    public void destroy() {
        log.info("Yibao异步通知接受Filter销毁");
    }

    protected String getDispatcherBeanName() {
        String beanName = getInitParameter(NOTIFY_DISPATCHER_BEAN_NAME_KEY);
        if (Strings.isBlank(beanName)) {
            beanName = DEFAULT_NOTIFY_DISPATCHER_BEAN_NAME;
        }
        return beanName;
    }
}
